package com.zablert.lazyutil.views.buttongroup;

import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.EventListenerList;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Iterator;

import static java.awt.event.ItemEvent.DESELECTED;
import static java.awt.event.ItemEvent.SELECTED;

/**
 *
 */
public class ZButtonGroup extends ButtonGroup {
    protected EventListenerList listenerList = new EventListenerList();
    protected EventListenerList childListenerList = new EventListenerList();
    private AbstractButton selectButton = null;

    public void add(AbstractButton... buttons) {
        for (AbstractButton button : buttons) {
            add(button);
        }
    }

    public void setSelected(AbstractButton button, boolean isSelected) {
        setSelected(button.getModel(), isSelected);
    }

    public void addGroupListener(IButtonGroupListener listener) {
        listenerList.add(IButtonGroupListener.class, listener);

        Iterator<AbstractButton> iterator = getElements().asIterator();
        while (iterator.hasNext()) {
            AbstractButton abstractButton = iterator.next();
            ItemListener itemListener = new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    if (e.getStateChange() == SELECTED) {
                        selectButton = (AbstractButton) e.getItem();
                        for (IButtonGroupListener groupListener : getGroupListeners()) {
                            groupListener.itemChangeSelect((AbstractButton) e.getItem());
                        }
                    } else if (e.getStateChange() == DESELECTED) {
                        for (IButtonGroupListener groupListener : getGroupListeners()) {
                            groupListener.itemChangeUnSelect((AbstractButton) e.getItem());
                        }
                    }
                }
            };
            childListenerList.add(ItemListener.class, itemListener);
            abstractButton.addItemListener(itemListener);
        }
    }

    public void removeGroupListener(IButtonGroupListener listener) {
        listenerList.remove(IButtonGroupListener.class, listener);
    }

    public IButtonGroupListener[] getGroupListeners() {
        return listenerList.getListeners(IButtonGroupListener.class);
    }

    @Nullable
    public AbstractButton getSelectButton() {
        return selectButton;
    }
}
